package com.polaris.live.popup.party

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.party.RoomManagementAdapter
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupRoomManagementBinding
import com.polaris.live.dialog.AdministratorDialog
import com.polaris.live.dialog.RoomSkinDialog
import com.polaris.live.dialog_fragment.TaskDialogFragment
import com.polaris.live.dialog_fragment.room_background.RoomBackgroundPopup
import com.polaris.live.im.sfs.bean.live.LiveRoomInfo
import com.polaris.live.interface_bag.XpopupCallBackImpl
import com.polaris.live.net.liveService
import com.polaris.live.popup.FeedBackPopup
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.bean.ManagementBean
import com.polaris.live.ui.party.utils.ManagementType
import com.polaris.live.utils.OtherPermissionUtils
import com.polaris.live.utils.TaskRedProxy
import com.polaris.live.utils.fragment.FragmentUtils
import com.polaris.live.viewmodel.GlobalViewModelProxy
import com.polaris.live.viewmodel.party.PartyAnchorFragmentModel

/**
 *  房间管理
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class RoomManagementPopup(
    context: Context,
    private val mAnchor: Boolean, //是不是房主
    private val roomType: Int, //0 语音房   1游戏房  2视频房
    private val isSeat: Boolean, //是否上座 只观众使用 mAnchor=false
    private val isOpenCamera: Boolean, //是否打开摄像头
    private val mLiveRoomInfo: LiveRoomInfo,
    private val mViewModel: PartyAnchorFragmentModel,
    private val mIsOpenGift: Boolean = true,
    private val mIsOpenSound: Boolean = true,
    private val onKeyboardStateListener: ((state: Boolean) -> Unit)? = null,
    private val onCloseBack: (() -> Unit)? = null,
    private val onBeauty: (() -> Unit)? = null,
    private val onSwitchCamera: (() -> Unit)? = null,
    private val onOpenCloseCamera: ((state: Boolean) -> Unit)? = null,
    private val onOpenGiftAnimation: ((state: Boolean) -> Unit)? = null,
    private val onOpenGiftSound: ((state: Boolean) -> Unit)? = null,
    private val onExitTherRoom: (() -> Unit)? = null,
    private val music: (() -> Unit)? = null,
    private val onUserClick: ((userId: Long) -> Unit)? = null, //用户点击需调起用户资料卡
    private val onMinimize: (() -> Unit)? = null, //最小化
    private val onInvitationFriend: (() -> Unit)? = null, //邀请好友
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupRoomManagementBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_room_management
    }

    private val mRoomAdapter by lazy { RoomManagementAdapter() }
    private val mMemberAdapter by lazy { RoomManagementAdapter() }
    private val mUserOperationAdapter by lazy { RoomManagementAdapter() }

    private val mLayoutManager by lazy {
        GridLayoutManager(
            context,
            5,
            GridLayoutManager.VERTICAL,
            false
        )
    }
    private val mMemberLayoutManager by lazy {
        GridLayoutManager(
            context,
            5,
            GridLayoutManager.VERTICAL,
            false
        )
    }
    private val mUserOperationLayoutManager by lazy {
        GridLayoutManager(
            context,
            5,
            GridLayoutManager.VERTICAL,
            false
        )
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupRoomManagementBinding.bind(popupImplView)
        if (AppCodeUtils.isAR()) {
            mBinding.roomLl.setBackgroundResource(R.drawable.shape_transparent_to_ffffff_10)
            mBinding.memberLl.setBackgroundResource(R.drawable.shape_transparent_to_ffffff_10)
            mBinding.userOperationLl.setBackgroundResource(R.drawable.shape_transparent_to_ffffff_10)
        }

        mRoomAdapter.setOnItemClickListener { _, _, position ->
            val data = mRoomAdapter.getItem(position)
            onItemClick(data)
        }
        mMemberAdapter.setOnItemClickListener { _, _, position ->
            val data = mMemberAdapter.getItem(position)
            onItemClick(data)
        }
        mUserOperationAdapter.setOnItemClickListener { _, _, position ->
            val data = mUserOperationAdapter.getItem(position)
            onItemClick(data)
        }
        mBinding.recyclerRoom.apply {
            adapter = mRoomAdapter
            layoutManager = mLayoutManager
        }
        mBinding.recyclerMember.apply {
            adapter = mMemberAdapter
            layoutManager = mMemberLayoutManager
        }
        mBinding.recyclerUserOperation.apply {
            adapter = mUserOperationAdapter
            layoutManager = mUserOperationLayoutManager
        }
        addData()
    }

    private fun addData() {
        /**
         * =======================房间设置========================
         */
        //房间背景
        if (roomType != 1 && mAnchor) {
            mRoomAdapter.addData(
                ManagementBean(
                    ManagementType.ROOM_BACKGROUND,
                    StringUtils.getString(string.room_background),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_room_background,
                    null,
                )
            )
        }
        if (mAnchor) {
            mRoomAdapter.addData(
                ManagementBean(
                    ManagementType.ROOM_SKIN,
                    StringUtils.getString(string.room_skin),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_room_skin,
                    null,
                )
            )
            //邀请好友
            mRoomAdapter.addData(
                ManagementBean(
                    ManagementType.INVITATION_FRIEND,
                    StringUtils.getString(string.invitation_friend),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_invitation_friend,
                    null,
                )
            )
        }
        //房间上锁
        if (mAnchor) {
            mRoomAdapter.addData(
                ManagementBean(
                    ManagementType.LOCK_THE_ROOM,
                    StringUtils.getString(string.lock_the_room),
                    null,
                    false,
                    2,
                    !mLiveRoomInfo.locked,
                    R.drawable.btn_lock_the_room1,
                    R.drawable.btn_lock_the_room2,
                )
            )
        }
        //反馈
        if (mLiveRoomInfo.userId == UserManager.getUserId()) { //是房主
            mRoomAdapter.addData(
                ManagementBean(
                    ManagementType.FEED_BACK,
                    StringUtils.getString(string.feedback),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_feedback,
                    null,
                )
            )
        }
        //有数据显示顶部
        mBinding.roomLl.visibility = if (mRoomAdapter.data.isEmpty()) View.GONE else View.VISIBLE
        /**
         * =======================成员设置========================
         */
        //管理员
        if (mAnchor) {
            mMemberAdapter.addData(
                ManagementBean(
                    ManagementType.ADMINISTRATOR,
                    StringUtils.getString(string.administrator),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_administrator,
                    null,
                )
            )
        }
        //成员费
        if (mAnchor) {
            mMemberAdapter.addData(
                ManagementBean(
                    ManagementType.ROOM_MEMBER,
                    StringUtils.getString(string.membership_fee),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_room_member,
                    null,
                )
            )
        }
        //进房条件
        if (mAnchor) {
            mMemberAdapter.addData(
                ManagementBean(
                    ManagementType.ROOM_CONDITION,
                    StringUtils.getString(string.check_in_conditions),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_room_condition,
                    null,
                )
            )
        }
        //有数据显示顶部
        mBinding.memberLl.visibility = if (mMemberAdapter.data.isEmpty()) View.GONE else View.VISIBLE

        /**
         * =======================个人操作========================
         */

        //礼物动效
        mUserOperationAdapter.addData(
            ManagementBean(
                ManagementType.GIFT_ANIMATION,
                StringUtils.getString(string.gift_animation),
                null,
                false,
                3,
                mIsOpenGift,
                R.drawable.btn_room_gift,
                null,
            ) { isSelected, position ->
                val data = mUserOperationAdapter.getItemOrNull(position)
                    ?: return@ManagementBean

                val state = data.state
                data.state = !state
                onOpenGiftAnimation?.invoke(!state)

                val indexOfFirst =
                    mUserOperationAdapter.data.indexOfFirst { it.operateId == ManagementType.AUDIO_ANIMATION }
                if (indexOfFirst != -1) {
                    val audioData = mUserOperationAdapter.getItemOrNull(indexOfFirst)
                        ?: return@ManagementBean
                    audioData.state = data.state
                    postNotifyItemChanged(indexOfFirst)
                }
                postNotifyItemChanged(position)
            }
        )

        //礼物音效
        mUserOperationAdapter.addData(
            ManagementBean(
                ManagementType.AUDIO_ANIMATION,
                StringUtils.getString(string.sound_string),
                null,
                false,
                3,
                mIsOpenSound,
                R.drawable.btn_room_sound,
                null,
            ) { isSelected, position ->
                val data = mUserOperationAdapter.getItem(position)
                val state = data.state
                //只有礼物动效开着，音效才能开
                val indexOfFirst =
                    mUserOperationAdapter.data.indexOfFirst { it.operateId == ManagementType.GIFT_ANIMATION }
                if (indexOfFirst == -1) return@ManagementBean
                val gift = mUserOperationAdapter.getItem(indexOfFirst)
                //如果礼物动效开着呢就通知下去
                if (gift.state) {
                    data.state = !state
                    onOpenGiftSound?.invoke(!state)
                } else {
                    //如果礼物动效关着呢就不要改变状态
                    data.state = false
                    onOpenGiftSound?.invoke(true)
                }
                postNotifyItemChanged(position)
            }
        )
        //音乐
        mUserOperationAdapter.addData(
            ManagementBean(
                ManagementType.MUSIC,
                StringUtils.getString(string.music),
                null,
                false,
                1,
                true,
                R.drawable.btn_room_audio,
                null,
            )
        )
        //摄像头和美颜设置
        if (roomType == 2) {
            if (isSeat) {
                if (isOpenCamera) {
                    mUserOperationAdapter.addData(
                        ManagementBean(
                            ManagementType.BEAUTY,
                            StringUtils.getString(string.beauty_beautify),
                            null,
                            false,
                            1,
                            true,
                            R.drawable.party_meiyan,
                            null,
                        )
                    )
                    mUserOperationAdapter.addData(
                        ManagementBean(
                            ManagementType.SWITCH_CAMERA,
                            StringUtils.getString(string.switch_camera),
                            null,
                            false,
                            1,
                            true,
                            R.drawable.party_switch,
                            null,
                        )
                    )
                }
                if (!mAnchor) { //视频房主播不能关闭摄像头
                    mUserOperationAdapter.addData(
                        ManagementBean(
                            ManagementType.OPEN_CLOSE_CAMERA,
                            StringUtils.getString(string.open_camera),
                            StringUtils.getString(string.close_camera),
                            false,
                            3,
                            isOpenCamera,
                            R.drawable.party_camera_1,
                            null
                        ) { isSelected, position ->
                            onOpenCloseCamera?.invoke(isSelected)
                            dismiss()
                        }
                    )
                }
            }
        }
        mUserOperationAdapter.addData(
            ManagementBean(
                ManagementType.TASK,
                StringUtils.getString(string.daily_tasks),
                null,
                TaskRedProxy.isRedAvailable(),
                1,
                true,
                R.drawable.task_room_btn,
                null,
            )
        )
        if (roomType == 0) { //是语音房
            mUserOperationAdapter.addData(
                ManagementBean(
                    ManagementType.MINIMIZE,
                    StringUtils.getString(string.minimize),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_minimize,
                    null,
                )
            )
        }
        if (!mAnchor) {
            //邀请好友
            mUserOperationAdapter.addData(
                ManagementBean(
                    ManagementType.INVITATION_FRIEND,
                    StringUtils.getString(string.invitation_friend),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_invitation_friend,
                    null,
                )
            )
        }
        //退出房间
        if (mLiveRoomInfo.userId == UserManager.getUserId()) { //是房主
            mUserOperationAdapter.addData(
                ManagementBean(
                    ManagementType.CLOSE_THE_ROOM,
                    StringUtils.getString(string.close_the_room),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_close_the_room,
                    null,
                )
            )
        }
        //关闭房间
        if (mAnchor) {
            mUserOperationAdapter.addData(
                ManagementBean(
                    ManagementType.EXIT_THE_ROOM,
                    StringUtils.getString(string.exit_the_room),
                    null,
                    false,
                    1,
                    true,
                    R.drawable.btn_leave_room,
                    null,
                )
            )
        }
        //有数据显示顶部
        mBinding.userOperationLl.visibility = if (mUserOperationAdapter.data.isEmpty()) View.GONE else View.VISIBLE
//            mAdapter.addData(
//                ManagementBean(
//                    ManagementType.WELCOME_MESSAGE,
//                    StringUtils.getString(string.welcome_message),
//                    null,
//                    1,
//                    true,
//                    R.drawable.btn_welcome_message,
//                    null,
//                )
//            )
    }

    private fun postNotifyItemChanged(index: Int) {
        mBinding.recyclerUserOperation.post {
            mUserOperationAdapter.notifyItemChanged(index)
        }
    }

    private fun onItemClick(data: ManagementBean) {
        when (data.operateId) {
            ManagementType.TURN_OFF_GIFT_EFFECTS -> {
                ToastGravity.showGravity(data.name)
            }

            ManagementType.ROOM_BACKGROUND -> {
                showRoomBackgroundPopup()
            }

            ManagementType.WELCOME_MESSAGE -> {
                showWelcomeMessagePopup()
            }

            ManagementType.LOCK_THE_ROOM -> {
                partyRoomLockPopup()
            }

            ManagementType.CLOSE_THE_ROOM -> {
                showClosePartyPopup()
            }

            ManagementType.FEED_BACK -> {
                XPopup.Builder(context)
                    .hasShadowBg(false)
                    .isDestroyOnDismiss(true)
                    .asCustom(FeedBackPopup(context, mViewModel))
                    .show()
            }

            ManagementType.ADMINISTRATOR -> {
                GlobalViewModelProxy.getAdministratorData(mViewModel) {
                    XPopup.Builder(context)
                        .hasShadowBg(false)
                        .isDestroyOnDismiss(true)
                        .asCustom(AdministratorDialog(context, mViewModel, it))
                        .show()
                }
            }

            ManagementType.BEAUTY -> {
                dismiss()
                onBeauty?.invoke()
            }

            ManagementType.SWITCH_CAMERA -> {
                dismiss()
                onSwitchCamera?.invoke()
            }

            ManagementType.EXIT_THE_ROOM -> {
                dismiss()
                onExitTherRoom?.invoke()
            }

            ManagementType.MUSIC -> {
                dismiss()
                music?.invoke()
            }

            ManagementType.ROOM_MEMBER -> {
                dismiss()
                MembershipFeePopup.show(context, mViewModel, mLiveRoomInfo.roomId ?: "", onUserClick)
            }

            ManagementType.ROOM_CONDITION -> {
                dismiss()
                SetEntryConditionsPopup.show(context, mViewModel, mLiveRoomInfo.roomId ?: "")
            }

            ManagementType.TASK -> {
                dismiss()
                val fragmentManager = FragmentUtils.getFragmentManager(context) ?: return
                TaskDialogFragment().show(fragmentManager, TaskDialogFragment.TAG)
            }

            ManagementType.MINIMIZE -> {
                dismiss()
                OtherPermissionUtils.checkAndRequestOverlayPermission(context) {
                    if (it) {
                        onMinimize?.invoke()
                    }
                }
            }

            ManagementType.INVITATION_FRIEND -> {
                dismiss()
                onInvitationFriend?.invoke()
            }
            ManagementType.ROOM_SKIN -> {
                RoomSkinDialog.show(context, mViewModel)
                dismiss()
            }
        }
    }

    /**
     * 显示房间背景
     */
    private fun showRoomBackgroundPopup() {
        val fragmentManager = FragmentUtils.getFragmentManager(context) ?: return
        RoomBackgroundPopup.show(fragmentManager, mLiveRoomInfo.userId)
    }

    /**
     * 显示WelcomeMessagePopup
     */
    private fun showWelcomeMessagePopup() {
        mViewModel.requestLoading(
            { liveService.welcomeSpeech() }, {
                if (it.allowedUpload) {
                    XPopup.Builder(context)
                        .hasShadowBg(true)
                        .isDestroyOnDismiss(true)
                        .setPopupCallback(object : XpopupCallBackImpl {
                            override fun onCreated(popupView: BasePopupView) {
                                onKeyboardStateListener?.invoke(false)
                            }

                            override fun onDismiss(popupView: BasePopupView) {
                                onKeyboardStateListener?.invoke(true)
                            }
                        })
                        .asCustom(WelcomeMessagePopup(context, it.content) { msg ->
                            mViewModel.welcomeSpeechUpdate(msg)
                        })
                        .show()
                } else {
                    ToastGravity.showGravity(string.welcome_message_edited)
                }

            },
            {
                ToastGravity.showGravity(it.errorMsg)
            }
        )
    }

    /**
     * 显示关闭语聊房确认弹窗
     */
    private fun showClosePartyPopup() {

        XPopup.Builder(context)
            .hasShadowBg(false)
            .isDestroyOnDismiss(true)
            .asCustom(ClosePartyPopup(
                context, mLiveRoomInfo.startTime
            ) {
                onCloseBack?.invoke()
            })
            .show()
    }

    /**
     * 显示partyRoomLockPopup
     */
    private fun partyRoomLockPopup() {
        mViewModel.requestLoading({ liveService.getPassword() }, {
            XPopup.Builder(context)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .setPopupCallback(object : XpopupCallBackImpl {
                    override fun onCreated(popupView: BasePopupView) {
                        onKeyboardStateListener?.invoke(false)
                    }

                    override fun onDismiss(popupView: BasePopupView) {
                        onKeyboardStateListener?.invoke(true)
                    }
                })
                .asCustom(PartyLockPopup(context, it.password, mViewModel) {
                    mRoomAdapter.data.forEachIndexed { index, managementBean ->
                        if (ManagementType.LOCK_THE_ROOM == managementBean.operateId) {
                            managementBean.state = !it
                            mRoomAdapter.notifyItemChanged(index)
                            return@forEachIndexed
                        }

                    }
                })
                .show()
        }, {
            ToastGravity.showGravity(it.errorMsg)
        })
    }
}